package com.framework.bdf4j.sysadm.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.framework.bdf4j.annotations.SysLog;
import com.framework.bdf4j.comm.Constants;
import com.framework.bdf4j.comm.persist.PageDomain;
import com.framework.bdf4j.comm.util.R;
import com.framework.bdf4j.comm.util.StringUtils;
import com.framework.bdf4j.comm.web.WebUtil;
import com.framework.bdf4j.sysadm.entity.SysFile;
import com.framework.bdf4j.sysadm.service.SysFileService;

import cn.hutool.core.io.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;


/**
 * 文件管理
 *
 */
@Controller
@AllArgsConstructor
@RequestMapping("/admin/file")
@Api(value = "file", tags = "文件管理")
public class SysFileController {
	private final SysFileService sysFileService;

	// 跳转到文件列表页
    @GetMapping("/index")
    public String goFile() {
        return "sysadm/file/fileList";
    }
    
	/**
	 * 分页查询
	 *
	 * @param page    分页对象
	 * @param sysFile 文件管理
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@ResponseBody
	@GetMapping("/page")
	public R getSysFilePage(Page page, PageDomain domain, SysFile sysFile) {
	    OrderItem orderitem = StringUtils.getOrderItem(domain);
        if (orderitem != null) {
            page.addOrder(orderitem);
        }
		return R.ok(sysFileService.page(page, Wrappers.query(sysFile)));
	}


	/**
	 * 通过id删除文件管理
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id删除文件管理", notes = "通过id删除文件管理")
	@SysLog("删除文件管理")
	@ResponseBody
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('sys_file_del')")
	public R removeById(@PathVariable Long id) {
		return R.ok(sysFileService.deleteFile(id));
	}

	/**
	 * 上传文件
	 * 文件名采用uuid,避免原始文件名中带"-"符号导致下载的时候解析出现异常
	 *
	 * @param file 资源
	 * @return R(/ admin / bucketName / filename)
	 */
	@PostMapping("/upload")
	public R upload(@RequestParam("file") MultipartFile file) {
		return sysFileService.uploadFile(file);
	}

	/**
	 * 获取文件
	 *
	 * @param fileName 文件空间/名称
	 * @param response
	 * @return
	 */
	@GetMapping("/{fileName}")
	public void file(@PathVariable String fileName, HttpServletResponse response, HttpServletRequest request) {
		sysFileService.getFile(fileName, response,request);
	}

	@ResponseBody
    @GetMapping("/getInitFileInfo")
    public List<List> getInitFileInfo(@RequestParam String fileId) {
        List<List> initList = new ArrayList<List>();
        List<String> dataList = new ArrayList<String>();
        List<Map<String,String>> configList = new ArrayList<Map<String,String>>();
        if(StringUtils.isNotEmpty(fileId))
        {
            String[] fids = StringUtils.split(fileId, ",");
            for(String fid : fids)
            {
                SysFile sysfile = sysFileService.getOne(Wrappers.<SysFile>query().lambda().eq(SysFile::getFileName, fid));
                String ext = FileUtil.extName(fid);
                if("jpg".equalsIgnoreCase(ext) || "png".equalsIgnoreCase(ext) || "gif".equalsIgnoreCase(ext) || "bmp".equalsIgnoreCase(ext) || "jpeg".equalsIgnoreCase(ext))
                {
                    dataList.add("<img src='" + sysFileService.getFileUrl(fid) + "' class='file-preview-image'>");
                }
                else
                {
                    dataList.add("<div class='file-preview-other'><h2><i class='glyphicon glyphicon-file'></i></h2>" + sysfile.getOriginal() + "</div>");
                }
                
                Map<String,String> cfgmap = new HashMap<String,String>(); 
                cfgmap.put("caption", sysfile.getOriginal());
                cfgmap.put("key", fid);
                cfgmap.put("url", WebUtil.getRequest().getContextPath() + "/admin/file/" + sysfile.getId().toString());
                cfgmap.put("size", sysfile.getFileSize().toString());
                configList.add(cfgmap);
                initList.add(dataList);
                initList.add(configList);
            }
        }
        
        return initList;
    }
}
